<?php
namespace App\Http\Controllers\Admin\Erqi;

use App\Service\Admin\Erqi\CheapService;
use Illuminate\Http\Request;

class CheapController extends BaseController
{
    //素材

    public function __construct(CheapService $service)
    {
        $this->db = $service;
    }

    //列表
    public function getIndex()
    {
        $res = $this->db->getList();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //更新
    public function modify(Request $request)
    {
        //$id = $request->post('id', 0);
        $gno = $request->post('gno', '');
        $pas['per'] = $request->post('per', '');
        $pas['start_time'] = $request->post('start_time', '');
        $pas['end_time'] = $request->post('end_time', '');
        if ($pas['per'] <= 0 || $pas['per'] > 100) {
            return $this->toJson(-2, '折扣率无效');
        }
        if (strlen($pas['per']) == 1) {
            $pas['per'] = $pas['per'] . '0';
        }
        if ($pas['start_time'] > $pas['end_time']) {
            return $this->toJson(-2, '开始时间不能晚于结束时间');
        }
        $res = $this->db->add($gno, $pas);
        if ($res['code'] < 0) {
            return $this->toJson($res['code'], $res['msg']);
        }
        return $this->toJson();
    }

    //删除
    public function del(Request $request)
    {
        $id = $request->post('id', 0);
        if (!$id) {
            return $this->toJson(-2, 'ID必须的');
        }
        $res = $this->db->setDel($id);
        if ($res['code'] < 0) {
            return $this->toJson($res['code'], $res['msg']);
        }
        return $this->toJson();
    }
}